<template>
  <div class="books">
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="书名">
          <el-input v-model="searchForm.title" placeholder="请输入书名" />
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="searchForm.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable>
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>图书列表</span>
          <div>
            <el-button type="primary" @click="handleAdd">添加图书</el-button>
          </div>
        </div>
      </template>
      
      <el-table
        :data="bookList"
        style="width: 100%"
        v-loading="loading"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="书名" />
        <el-table-column prop="author" label="作者" />
        <el-table-column prop="publisher" label="出版社" />
        <el-table-column prop="categoryName" label="分类" />
        <el-table-column prop="pages" label="页数" width="80" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑图书对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="bookFormRef"
        :model="bookForm"
        :rules="bookRules"
        label-width="80px"
      >
        <el-form-item label="书名" prop="title">
          <el-input v-model="bookForm.title" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="bookForm.author" />
        </el-form-item>
        <el-form-item label="ISBN" prop="isbn">
          <el-input v-model="bookForm.isbn" />
        </el-form-item>
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="bookForm.publisher" />
        </el-form-item>
        <el-form-item label="出版日期" prop="publishDate">
          <el-date-picker
            v-model="bookForm.publishDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="页数" prop="pages">
          <el-input-number
            v-model="bookForm.pages"
            :min="1"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="bookForm.categoryId" placeholder="请选择分类">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="bookForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBook">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'Books',
  setup() {
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const bookFormRef = ref(null)
    
    // 搜索表单
    const searchForm = reactive({
      title: '',
      author: '',
      categoryId: ''
    })
    
    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 图书表单
    const bookForm = reactive({
      id: null,
      title: '',
      author: '',
      isbn: '',
      publisher: '',
      publishDate: '',
      pages: null,
      categoryId: '',
      description: ''
    })
    
    // 表单验证规则
    const bookRules = {
      title: [
        { required: true, message: '请输入书名', trigger: 'blur' }
      ],
      author: [
        { required: true, message: '请输入作者', trigger: 'blur' }
      ]
    }
    
    // 模拟分类数据
    const categories = ref([
      { id: 1, name: '技术' },
      { id: 2, name: '文学' },
      { id: 3, name: '历史' },
      { id: 4, name: '哲学' }
    ])
    
    // 模拟图书数据
    const bookList = ref([
      {
        id: 1,
        title: 'Vue.js设计与实现',
        author: '霍春阳',
        isbn: '9787115593146',
        publisher: '人民邮电出版社',
        publishDate: '2022-07-01',
        pages: 400,
        categoryId: 1,
        categoryName: '技术',
        description: '这是一本关于Vue.js框架设计原理的深度解析书籍',
        createTime: '2023-05-15 10:00:00'
      },
      {
        id: 2,
        title: 'JavaScript高级程序设计',
        author: 'Nicholas C. Zakas',
        isbn: '9787115216181',
        publisher: '人民邮电出版社',
        publishDate: '2008-05-01',
        pages: 820,
        categoryId: 1,
        categoryName: '技术',
        description: 'JavaScript经典教材',
        createTime: '2023-05-10 14:30:00'
      }
    ])
    
    // 设置分页总数
    pagination.total = bookList.value.length
    
    const handleSearch = () => {
      ElMessage.info('执行搜索')
    }
    
    const resetSearch = () => {
      searchForm.title = ''
      searchForm.author = ''
      searchForm.categoryId = ''
      ElMessage.info('重置搜索条件')
    }
    
    const handleAdd = () => {
      dialogTitle.value = '添加图书'
      // 重置表单
      Object.keys(bookForm).forEach(key => {
        bookForm[key] = key === 'pages' ? null : ''
      })
      dialogVisible.value = true
    }
    
    const handleEdit = (row) => {
      dialogTitle.value = '编辑图书'
      // 填充表单数据
      Object.keys(bookForm).forEach(key => {
        bookForm[key] = row[key]
      })
      dialogVisible.value = true
    }
    
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除图书《${row.title}》吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 模拟删除操作
        const index = bookList.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          bookList.value.splice(index, 1)
          pagination.total--
          ElMessage.success('删除成功')
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }
    
    const confirmBook = () => {
      bookFormRef.value.validate((valid) => {
        if (valid) {
          if (bookForm.id) {
            // 编辑操作
            const index = bookList.value.findIndex(item => item.id === bookForm.id)
            if (index !== -1) {
              // 更新分类名称
              const category = categories.value.find(c => c.id === bookForm.categoryId)
              bookForm.categoryName = category ? category.name : ''
              
              // 更新数据
              Object.keys(bookForm).forEach(key => {
                bookList.value[index][key] = bookForm[key]
              })
              ElMessage.success('编辑成功')
            }
          } else {
            // 添加操作
            const newBook = {
              id: bookList.value.length + 1,
              ...bookForm,
              createTime: new Date().toLocaleString()
            }
            
            // 设置分类名称
            const category = categories.value.find(c => c.id === bookForm.categoryId)
            newBook.categoryName = category ? category.name : ''
            
            bookList.value.unshift(newBook)
            pagination.total++
            ElMessage.success('添加成功')
          }
          
          dialogVisible.value = false
        } else {
          ElMessage.error('请填写正确的信息')
        }
      })
    }
    
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      ElMessage.info(`每页 ${val} 条`)
    }
    
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      ElMessage.info(`当前页: ${val}`)
    }
    
    return {
      loading,
      dialogVisible,
      dialogTitle,
      bookFormRef,
      searchForm,
      pagination,
      bookForm,
      bookRules,
      categories,
      bookList,
      handleSearch,
      resetSearch,
      handleAdd,
      handleEdit,
      handleDelete,
      confirmBook,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>